package org.jsping.loginservlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.jsping.entity.User;
import org.jsping.service.ILoginUserService;
import org.jsping.service.impl.LoginUserServiceImpl;

/*
 * 处理用户登录请求的servlet
 */
@WebServlet("/UserLoginServlet.do")
public class UserLogin extends HttpServlet{
	//用户登录/注册业务处理
	private ILoginUserService loginUser = new LoginUserServiceImpl();
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String user = req.getParameter("username");
		String pwd = req.getParameter("password");
		System.out.println("user:"+user+",pwd:"+pwd);
		User u = loginUser.login(user, pwd);
		System.out.println(u);
		boolean judge = false;
		//如果用户存在，那么写入一个session和cookie（用户信息）
		if(u!=null) {
			judge = true;
			Cookie uname = new Cookie("uname", u.getUname());
			Cookie uimg = new Cookie("img", u.getImage());
			Cookie usex = new Cookie("sex", u.getSex()+"");
			Cookie uid = new Cookie("uid", u.getUid()+"");
			resp.addCookie(uname);
			resp.addCookie(uimg);
			resp.addCookie(usex);
			resp.addCookie(uid);
			HttpSession session = req.getSession();
			session.setMaxInactiveInterval(60*10);
			session.setAttribute("user", "user");
		}
		resp.getWriter().print(judge);
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		this.doGet(req, resp);
	}
}
